package com.niit.session19;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CURDDemo {
	public static void main(String[] args) {
		CURDDemo curdDemo = new CURDDemo();
		try {
//			boolean addStudent = curdDemo.addStudent(new Student("001","Trout","男",3,2));
//			if(addStudent) {
//				System.out.println("添加成功");
//			}
			List<Student> listStudent = curdDemo.listStudent();
			for (Student student : listStudent) {
				System.out.println(student);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
//	增删改查独立的四个方法
	public boolean addStudent(Student student) throws SQLException {
		Connection conn = JDBCUtil.getConn();
		Statement statement = conn.createStatement();
//		建议优化成StringBuilder
		String sql = "insert into student value('" + student.getSid() + "','" + student.getName() + "','"
				+ student.getGender() + "'," + student.getBatch() + "," + student.getGroupLeader()+")";
		System.out.println(sql);
//		executeUpdate方法返回一个int值，这个值是指这条sql语句指向后数据库受影响的行数
		int update = statement.executeUpdate(sql);
//		链接关闭
		JDBCUtil.close(conn, statement, null);
		return update > 0 ? true : false;
	}

	/**
	 * 批量查询
	 * 
	 * @return
	 * @throws SQLException
	 */
	public List<Student> listStudent() throws SQLException {
		Connection conn = JDBCUtil.getConn();
		Statement statement = conn.createStatement();
		ResultSet rs = statement.executeQuery("select * from student");
		List<Student> students = new ArrayList<Student>();
		while (rs.next()) {
			students.add(new Student(rs.getString("sid"), rs.getString("name"), rs.getString("gender"),
					rs.getInt("batch"), rs.getInt("group_leader")));
		}
		JDBCUtil.close(conn, statement, rs);
		return students;

	}
}
